package cn.nexd.app.presenter;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;


import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.nexd.app.activity.SignInActivity;
import cn.nexd.app.activity.inter.ILoadingActivityView;
import cn.nexd.app.NexdApplication;
import cn.nexd.app.model.ExpandableModel;
import cn.nexd.app.model.MallModel;
import cn.nexd.app.model.OperaRecord;
import cn.nexd.app.model.UserInfo;
import cn.nexd.app.okhttp.Call;
import cn.nexd.app.okhttp.Response;
import cn.nexd.app.okhttp.android.OkHttpUtils;
import cn.nexd.app.okhttp.android.callback.Callback;
import cn.nexd.app.orm.db.assit.QueryBuilder;
import cn.nexd.app.perimission.CheckPermission;
import cn.nexd.app.presenter.inter.ILoadingPresenter;
import cn.nexd.app.util.FileUtil;
import cn.nexd.app.util.MySqlLiteOpenHelper;
import cn.nexd.app.util.UrlUtil;

/**
 * MVP:
 * 处理Loading 页面的所有业务逻辑
 * <p/>
 * Created by wangxu on 16/3/28.
 */
public class ILoadingPresenterImpl implements ILoadingPresenter, MySqlLiteOpenHelper.ModelT<Map<String, UserInfo>> {
    private Context context;
    private StringBuffer userFilePath; // 用户名文件存储目录位置
    private StringBuffer mallFilePath; // 待采集的商场文件存储位置
    private ILoadingActivityView iLoadingActivityView; // 载入页面
    private static final String POSITON_COLLECTOR = "2";
    private String dbPath;
    private MySqlLiteOpenHelper dbHelper;


    public ILoadingPresenterImpl(Context context, ILoadingActivityView iLoadingActivityView) {
        this.context = context;
        this.iLoadingActivityView = iLoadingActivityView;
        userFilePath = new StringBuffer();
        mallFilePath = new StringBuffer();
        userFilePath.append(NexdApplication.BASE_FILE_PATH)
                .append(File.separator)
                .append(NexdApplication.CONFIG)
                .append(File.separator)
                .append(NexdApplication.USER_CONFIG);
        mallFilePath.append(NexdApplication.BASE_FILE_PATH)
                .append(File.separator)
                .append(NexdApplication.CONFIG)
                .append(File.separator)
                .append(NexdApplication.MALL_CONFIG);
        dbHelper = NexdApplication.getInstance().getDbHelper();
        dbPath = NexdApplication.getInstance().getDB_PATH();

    }


    @Override
    public void uploadOperaRecord() {
        // 查询数据库,获取所有未上传的操作记录    0 : 未上传   1 : 已上传
        QueryBuilder<OperaRecord> qb = new QueryBuilder<OperaRecord>(OperaRecord.class)
                .where("upload=?", new Integer[]{NexdApplication.NO_UPLOAD});
        final List<OperaRecord> operaRecords = NexdApplication.liteOrm.query(qb);
        if (operaRecords != null && operaRecords.size() != 0) {
            // 准备JSON数据, 装填数据, 准备上传参数
            JSONArray jsonArray = new JSONArray();
            for (OperaRecord operaRecord : operaRecords) {
                JSONObject uploadJson = new JSONObject();
                try {
                    uploadJson.put("startTime", operaRecord.getStartTime())
                            .put("endTime", operaRecord.getEndTime())
                            .put("lat", operaRecord.getLat())
                            .put("lng", operaRecord.getLng())
                            .put("userName", operaRecord.getUserName())
                            .put("operaRecord", operaRecord.getOperaRecord())
                            .put("mallName", operaRecord.getMallName())
                            .put("buildingId", operaRecord.getBuildingid())
                            .put("memo", operaRecord.getMemo())
                            .put("createTime", operaRecord.getCreateTime())
                            .put("type", operaRecord.getType());
                    jsonArray.put(uploadJson);
                } catch (JSONException e) {
                    MobclickAgent.reportError(context, e);
                    e.printStackTrace();
                }
            }
            Log.d("jsonArray", jsonArray.toString());


            StringBuilder uploadUrl = new StringBuilder();
            uploadUrl.append(UrlUtil.BASE_IP)
                    .append("aipLog/v1.0/apiRreceiveLog.do");

            Log.d("uoloadUrl ", uploadUrl.toString());
            // 准备上传 到后台接口, 生成很大很大的json
            OkHttpUtils.post().url(uploadUrl.toString())
                    .addParams("jsonData", jsonArray.toString())
                    .addParams("appKey", NexdApplication.APPKEY)
                    .build()
                    .execute(
                            new Callback<JSONObject>() {
                                @Override
                                public JSONObject parseNetworkResponse(Response response) throws Exception {
                                    return new JSONObject(response.body().string());
                                }

                                @Override
                                public void onError(Call call, Exception e) {
                                    MobclickAgent.reportError(context, e);
                                    updateUserConfig();
                                }

                                @Override
                                public void onResponse(JSONObject response) {
                                    Log.d("uploadResponse", response.toString());
                                    try {
                                        if (response.getBoolean("isSuccess")) {
                                            for (OperaRecord operaRecord : operaRecords) {
                                                operaRecord.setIsUpload(NexdApplication.UPLOADED);
                                            }

                                            NexdApplication.liteOrm.update(operaRecords);
                                        }
                                        updateUserConfig();
                                    } catch (JSONException e) {
                                        MobclickAgent.reportError(context, e);
                                        updateUserConfig();
                                        e.printStackTrace();
                                    }
                                }
                            });
        } else {
            updateUserConfig();
        }

    }

    @Override
    public void updateUserConfig() {
        StringBuilder userUrl = new StringBuilder();
        userUrl.append(UrlUtil.BASE_IP)
                .append("user/v1.0/getUsers.do");
        Log.d("updateUserUrl", userUrl.toString());
        OkHttpUtils.post().url(userUrl.toString())
                .addParams("positionId", POSITON_COLLECTOR)
                .addParams("appKey", NexdApplication.APPKEY)
                .build()
                .execute(new Callback<String>() {
                    @Override
                    public String parseNetworkResponse(Response response) throws Exception {
                        String result = response.body().string();
                        Log.d("userResult", result);
                        if (!TextUtils.isEmpty(result)) {
                            JSONObject rstJson = new JSONObject(result);
                            if (rstJson.getBoolean("isSuccess")) {
                                if (!CheckPermission.checkPermission((Activity) context, "android.permission.READ_EXTERNAL_STORAGE")) {
                                    iLoadingActivityView.showToast("设备存储权限被拒绝,无法正常使用!");
                                    return null;
                                }
                                dbHelper.delete(null, null);
                                List<Map<String, String>> info = new ArrayList<Map<String, String>>();
                                JSONArray usersArray = rstJson.getJSONArray("users");
                                for (int i = 0; i < usersArray.length(); i++) {
                                    JSONObject userJson = usersArray.getJSONObject(i);
                                    Map<String, String> map = new HashMap<String, String>();
                                    map.put("userName", userJson.getString("userName"));
                                    map.put("userMail", userJson.getString("userMail"));
                                    map.put("userPassword", userJson.getString("userPassword"));
                                    info.add(map);

                                }
                                dbHelper.insert(info);
                            } else {
                                iLoadingActivityView.showToast(rstJson.getString("msg"));
                            }
                        }
                        return "成功";
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        MobclickAgent.reportError(context, e);
                        checkUserExist();
                        enterLoginActivity();
                    }

                    @Override
                    public void onResponse(String response) {
                        Log.d("requestUsers", response);
                        DBAsyncTask dbAsyncTask = new DBAsyncTask();
                        dbAsyncTask.execute();
                        enterLoginActivity();

                    }
                });
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void checkUserExist() {

        if (!CheckPermission.checkPermission((Activity) context, "android.permission.READ_PHONE_STATE")) {
            iLoadingActivityView.showToast("设备存储权限被拒绝,无法正常使用!");
            return;
        }

        if (FileUtil.checkExist(dbPath)) {
//            readUserConfig(/*userFilePath.toString()*/);
            DBAsyncTask dbAsyncTask = new DBAsyncTask();
            dbAsyncTask.execute();
        } else {
            iLoadingActivityView.showToast("未找到相关配置文件,系统将在3秒后关闭");
            try {
                Thread.sleep(3000);
                ((Activity) context).finish();
            } catch (InterruptedException e) {
                MobclickAgent.reportError(context, e);
                e.printStackTrace();
            }
        }
    }


    @Override
    public void startLocation() {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.getProvider(LocationManager.GPS_PROVIDER) == null) {
            //无法定位：1、提示用户打开定位服务；2、跳转到设置界面
        } else {
            /**
             * 进行定位
             * provider:用于定位的locationProvider字符串:LocationManager.NETWORK_PROVIDER/LocationManager.GPS_PROVIDER
             * minTime:时间更新间隔，单位：ms
             * minDistance:位置刷新距离，单位：m
             * listener:用于定位更新的监听者locationListener
             */
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                return;
            }

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100l, 100f, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    NexdApplication.lat = String.valueOf(location.getLatitude());
                    NexdApplication.lng = String.valueOf(location.getLongitude());

                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {

                }

                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }
            });

        }
    }

    private void enterLoginActivity() {
        context.startActivity(new Intent(context, SignInActivity.class));
        ((Activity) context).finish();
    }

    public void readUserConfig() {
        Cursor cursor = dbHelper.selectCursor("select * from user", null);
        if (cursor.getCount() == 0) {
            return;
        }
        while (cursor.moveToNext()) {
            String userMail = cursor.getString(cursor.getColumnIndex("userMail"));
            String userName = cursor.getString(cursor.getColumnIndex("userName"));
            String userPassword = cursor.getString(cursor.getColumnIndex("userPassword"));
            UserInfo userInfo = new UserInfo(userName, userMail, userPassword);
            NexdApplication.user.put(userMail, userInfo);
        }
    }


    @Override
    public Map<String, UserInfo> Model(Cursor cursor) {
        Map<String, UserInfo> map = new HashMap<String, UserInfo>();
        String userEmail = cursor.getString(cursor.getColumnIndex("userEmail"));
        String userPassword = cursor.getString(cursor.getColumnIndex("userPassword"));
        String userName = cursor.getString(cursor.getColumnIndex("userName"));
        UserInfo userInfo = new UserInfo(userName, userEmail, userPassword);
        map.put(userEmail, userInfo);
        return map;
    }


    class DBAsyncTask extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {
            readUserConfig();
            return null;
        }
    }
}
